package com.zhx.threadcoreknowledge.threadobjectclasscommonmethod;

import java.util.Date;
import java.util.LinkedList;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-03 15:31
 * 用途         ： 用wait/notify 来实现消息队列
 */
public class ProduceConusmerModel {

    private EventStorage storage = new EventStorage();

    private static ProduceConusmerModel self = new ProduceConusmerModel();

    public static void main(String[] args) {
        Thread produce = new Thread(self.new Produce(self.storage));
        Thread consumer = new Thread(self.new Consumer(self.storage));

        produce.start();
        consumer.start();
    }

    class Produce implements Runnable{
        private EventStorage storage;

        public Produce(EventStorage storage){
            this.storage=storage;
        }

        @Override
        public void run() {
            for (int i = 0; i <100 ; i++) {
                storage.put();
            }
        }
    }

    class Consumer implements Runnable{
        private EventStorage storage;

        public Consumer(EventStorage storage){
            this.storage=storage;
        }

        @Override
        public void run() {
            for (int i = 0; i <100 ; i++) {
                storage.take();
            }
        }
    }

    class EventStorage{

        private int maxsize;

        private LinkedList<Date> list;

        public EventStorage(){
            maxsize=10;
            list= new LinkedList<>();
        }

        public synchronized void put(){
            while(list.size() == maxsize){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(new Date());
            System.out.println("添加了一个产品,当前队列的数量"+ list.size());
            notify();
        }


        public synchronized void take(){
            while(list.size() == 0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("消费了:"+list.poll()+"当前剩余:"+list.size());
            notify();
        }
    }
}
